package GenericStudy.Exa5;

import java.util.Arrays;

/**
 * 实现泛型二分查找方法
 */
public class BinSearch {
    /**
     * 泛型方法：二分查找
     * @param array 查找数组
     * @param key 查找元素
     * @param <T> 类型变量
     * @return
     */
    public static <T extends Comparable<T>>  int search(T[] array, T key) {
        int low = 0;
        int mid;
        int high = array.length;
        //二分查找法进行查找
        while (low <= high) {
            mid = (low + high) / 2;
            System.out.print(mid+" ");
            if (key.compareTo(array[mid]) > 0) {
                low = mid + 1;
            } else if (key.compareTo(array[mid]) < 0) {
                high = mid - 1;
            } else {
                System.out.println();
                return mid;
            }
        }
        return -1;
    }

    /**
     * 二分查找泛型方法测试
     * @param args
     */
    public static void main(String[] args) {
        Integer[] ints = {1,2,3,4,5,6,7,8,9,10};
        System.out.println("数据集合：");
        System.out.println(Arrays.toString(ints));
        System.out.println("元素7所对于的索引序号："+search(ints, 7));
    }
}
